<template>
  <div
    v-if="show"
    style="display: flex; flex-wrap: wrap"
    :style="{ minHeight: size[1] + 'px' }"
  >
    <div v-for="(url, index) in file_list" :key="index" class="files">
      <video controls :src="url" :height="size[1] + 'px'" />
      <div class="btns other-btn">
        <i class="el-icon-delete btn del" @click="fileRemove(index)" />
      </div>
    </div>

    <uploader
      ref="uploader"
      :auto-start="false"
      :options="options"
      :file-status-text="statusText"
      class="uploader-example"
      @file-added="onFileAdded"
      @file-success="onFileSuccess"
      v-show="file_list.length < limit && !loading"
      :style="{
        width: size[0] + 'px',
        height: size[1] + 'px',
      }"
    >
      <uploader-btn class="uploader-btn">
        <i class="el-icon-upload"></i>
      </uploader-btn>
    </uploader>
  </div>
</template>

<script>
// npm i vue-simple-uploader

/** main.js */
// import uploader from "vue-simple-uploader";
// Vue.use(uploader);
export default {
  props: {
    value: {
      type: Array,
      default: () => {
        return [];
      },
    },
    limit: {
      type: [String, Number],
      default: 1,
    },
    size: {
      type: Array,
      default: () => {
        return [160, 160];
      },
    },
    fileSize: {
      type: [String, Number],
      default: 200,
    },
  },
  data() {
    return {
      options: {
        target: function (file, chunkFile) {
          const key = "chunk_" + chunkFile.offset; // 键值 用于获取分块链接URL
          return file.chunkUrlData[key];
        },
        testChunks: false,
        chunkSize: 5 * 1024 * 1024,
        forceChunkSize: true,
        query: function (file, chunkFile) {
          const data = { partNumber: chunkFile.offset + 1 };
          return data;
        },
        uploadMethod: "PUT",
        method: "octet",
        processParams: function () {
          return {};
        },
      },
      statusText: {
        success: "成功了",
        error: "出错了",
        uploading: "上传中",
        paused: "暂停中",
        waiting: "等待中",
      },
      file_list: [],
      loading: false,
      uploadLoading: null,
      show: true,
    };
  },
  mounted() {
    this.$nextTick(() => {
      window.uploader = this.$refs.uploader.uploader;
    });
    if (this.value && this.value.length > 0) {
      this.file_list = [...this.value];
    }
  },
  watch: {
    value(list) {
      if (list && list.length > 0) {
        this.file_list = [...list];
      }
    },
  },
  methods: {
    selectFile() {
      window.uploader.addFile();
    },
    fileRemove(i) {
      this.show = false;
      if (this.file_list && this.file_list.length > 0) {
        this.file_list.splice(i, 1);
      } else {
        this.file_list = [];
      }
      this.$emit("input", this.file_list);
      setTimeout(() => {
        this.show = true;
        this.$nextTick(() => {
          window.uploader = this.$refs.uploader.uploader;
        });
      }, 500);
    },
    onFileAdded(file) {
      if (file.size / (1024 * 1024) > this.fileSize) {
        this.$message({
          type: "error",
          message: `视频不能大于${this.fileSize}MB`,
        });
        this.show = false;
        setTimeout(() => {
          this.show = true;
          this.$nextTick(() => {
            window.uploader = this.$refs.uploader.uploader;
          });
        }, 500);
        return;
      }
      if (file.fileType.indexOf("video/") == -1) {
        this.$message({
          type: "error",
          message: `请选择视频`,
        });
        this.show = false;
        setTimeout(() => {
          this.show = true;
          this.$nextTick(() => {
            window.uploader = this.$refs.uploader.uploader;
          });
        }, 500);
        return;
      }
      this.getChunkUploadUrl(file);
    },
    closeLoading() {
      this.loading = false;
      if (this.uploadLoading) this.uploadLoading.close();
    },
    async getChunkUploadUrl(file) {
      const fileName = file.name;
      const chunkSize = file.chunks.length;
      this.loading = true;
      this.uploadLoading = this.$loading({
        lock: true,
        text: "上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      await this.$http
        .get("/api/blade-resource/oss/endpoint/createMultipartUpload", {
          params: {
            fileName: fileName,
            chunkSize: chunkSize,
          },
        })
        .then((response) => {
          const data = response.data.data;
          file.link_url = data.link;
          file.file_name = data.name;
          file.chunkUrlData = {
            uploadId: data.uploadId,
          };
          data.urlList.forEach((url, index) => {
            file.chunkUrlData["chunk_" + index] = url;
          });
          window.uploader.resume();
        })
        .catch(function (error) {
          this.closeLoading();
          console.error("getChunkUploadUrl-error", error);
          this.$message.error("上传失败");
        });
    },
    // 单个文件上传成功
    onFileSuccess(rootFile, file) {
      const fileName = file.file_name; // 文件名
      const uploadId = file.chunkUrlData.uploadId; // uploadId
      console.log();
      this.$http({
        url: "/api/blade-resource/oss/endpoint/mergeMultipartUpload",
        params: {
          fileName: fileName,
          uploadId: uploadId,
        },
        timeout: 1000 * 60 * 2,
      })
        .then(() => {
          this.closeLoading();
          this.file_list.push(file.link_url);
          this.$emit("input", this.file_list);
          this.$message.success("上传成功");
        })
        .catch((error) => {
          this.closeLoading();
          console.error("onFileSuccess-error", error);
          this.$message.error("上传失败");
          this.fileRemove(this.file_list.length - 1);
        });
    },
  },
};
</script>

<style scoped lang="scss">
.uploader-example {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  box-shadow: none;

  .uploader-btn {
    border: 1px dashed #c0ccda !important;
    border: none;
    font-size: 28px;
    color: #8c939d;
    background: #fff;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    margin-top: 10px;
  }
  .uploader-btn:hover {
    border: 1px dashed #1880c9 !important;
    cursor: pointer;
  }
}
.files {
  position: relative;
  margin: 10px;
  padding: 2px;
  border-radius: 5px;
  flex-shrink: 1;
}
.btns {
  position: absolute;
  right: 0;
  top: 0;
  z-index: 999;
  background: rgba($color: #000000, $alpha: 0.2);
  border-radius: 5px;

  .btn {
    font-size: 24px;
    margin: 10px;
    cursor: pointer;
  }

  .show {
    color: #ee0000;
  }
  .del {
    color: #f56c6c;
  }
}

::v-deep .el-upload--picture-card {
  width: 100% !important;
  height: 100% !important;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
